package main

import (
	"fmt"
	"reflect"
)

func refType(obj any) {
	typeObj := reflect.TypeOf(obj)
	fmt.Println(typeObj, typeObj.Kind())
	// 去判断具体的类型
	switch typeObj.Kind() {
	case reflect.Slice:
		fmt.Println("切片")
	case reflect.Map:
		fmt.Println("map")
	case reflect.Struct:
		fmt.Println("结构体")
	case reflect.String:
		fmt.Println("字符串")
	}
}

func refValue(obj any) {
	value := reflect.ValueOf(obj)
	fmt.Println(value, value.Type())
	switch value.Kind() {
	case reflect.Int:
		fmt.Println(value.Int())
	case reflect.Struct:
		fmt.Println(value.Interface())
	case reflect.String:
		fmt.Println(value.String())

	}
}
func main() {
	refType(struct {
		Name string
	}{
		Name: "John",
	})
	name := "John"
	refType(name)
	refType([]string{"John", "Jane"})
	fmt.Println("--------------------------------")
	refValue(struct {
		Name string
	}{
		Name: "John",
	})
	refValue(name)
	refValue([]string{"John", "Jane"})
	fmt.Println("--------------------------------")
	refSetValue(&name)
	fmt.Println(name)
	fmt.Println("--------------------------------")
	s := Student{
		Name: "枫枫",
		Age:  18,
	}
	t := reflect.TypeOf(s)
	v := reflect.ValueOf(s)
  
	for i := 0; i < t.NumField(); i++ {
	  field := t.Field(i)
	  jsonField := field.Tag.Get("json")
	  if jsonField == "" {
		// 说明json的tag是空的
		jsonField = field.Name
	  }
	  fmt.Printf("Name: %s, type: %s, json: %s, value: %v\n", field.Name, field.Type, jsonField, v.Field(i))
	}
}

type Student struct {
	Name string
	Age  int `json:"age"`
}

func refSetValue(obj any) {
	value := reflect.ValueOf(obj)
	elem := value.Elem()
	//专门去指针的反设值
	switch elem.Kind() {
	case reflect.String:
		elem.SetString("枫枫知道")
	}
}
